// Promise是一个构造函数
//  构造函数有两个属性。PromiseState   PromiseResult

function Promise(executor){
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    let resolve = (value)=>{
        if(this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
    }
    let reject = (reason)=>{
        if(this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
    }
    try{
        executor(resolve,reject);
    }catch(e){
        reject(e);
    }
}
// 1. 添加then方法
// 2. 在哪里添加？
/**
 * 
 * @param {*} onResolved : 成功的回调
 * @param {*} onRejected ： 失败的回调
 */
Promise.prototype.then = function(onResolved, onRejected){
    // 如果状态是成功的，那么执行then成功的回调
    if(this.PromiseState === 'fulfilled'){
        // 将成功的结果值传递
        onResolved(this.PromiseResult);
    }
    // 如果状态是失败的，那么执行失败的回调
    if(this.PromiseState === 'rejected'){
        // 将失败的结果值传递
        onRejected(this.PromiseResult);
    }
}